<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"/>
	<link id="easyuiTheme" rel="stylesheet" type="text/css" href="../jquery-easyui-1.5.3/themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="../jquery-easyui-1.5.3/themes/icon.css"/>
	<!-- 注释掉这行后，按钮大小变正常了
	<link rel="stylesheet" type="text/css" href="../jquery-easyui-1.5.3/demo/demo.css"/>
	-->
    <script type="text/javascript" src="../jquery-easyui-1.5.3/jquery.min.js"></script>
    <script type="text/javascript" src="../jquery-easyui-1.5.3/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="../jquery-easyui-1.5.3/locale/easyui-lang-zh_CN.js"></script>
    <script type="text/javascript">
	    var contextPath = function() {
	        return  "/" + location.pathname.split("/")[1];
	    }
	    
		function getValue(name){
			var str=window.location.search;
			if (str.indexOf(name)!=-1){
				var pos_start=str.indexOf(name)+name.length+1;
				var pos_end=str.indexOf("&",pos_start);
				if (pos_end==-1){
					return str.substring(pos_start);
				} else {
					return str.substring(pos_start,pos_end);
				}
			} else {
				return "";
			}
		}
		
		var  themeName = getValue("theme");
		if (themeName!=""){
		    var cssurl  = $('#easyuiTheme').attr('href');  
		    var href = cssurl.substring(0, cssurl.indexOf('themes')) + 'themes/' + themeName + '/easyui.css';  
		    $('#easyuiTheme').attr('href', href);  
		}
	</script>

</head>

<style>
    .datagrid-btable{
        width:100%;
    }
    .datagrid-header-inner{
        width:100%;
    }
    .datagrid-header{
        width:100%;
    }
    .datagrid-htable{
        width:100%;
    }
    .datagrid-cell{margin:auto;}
    .fitem{text-align:center}
    .ftitle{text-align:center}
</style>

<body>
<div class="easyui-layout" data-options="fit:true">
    <div data-options="region:'center',title:'用户列表'">
		<table id="datagrid"  class="easyui-datagrid" style="width:100%;height:100%"></table>
		<div id="dgtoolbar">
			<form id="searchform" name="searchform" method="post" action="" >
				<td width="70" height="30">
					<strong>用户名：</strong>
					<input class="easyui-textbox" type="text" id="search_username" name="username" size=20 >
				</td>
				<td width="70" height="30">
					<strong>中文名：</strong>
					<input class="easyui-textbox" type="text" id="search_name_cn" name="name_cn" size=20 >
				</td>
				<td width="70" height="30">
					<strong>用户状态：</strong>
					<select class="easyui-combobox" id="search_userstatus" name="status" editable="false" style="width:100px;"></select>
				</td>
				<td height="30">
					<a id="submit_search">搜索</a>
					<a id="reset_search">重置</a>
				</td>
			</form>
		</div>
    </div>
</div>


</body>

    <script type="text/javascript">
	//页面内的全局变量，用于存储后台获得的用户状态enum
	var UserStateEnum ;

    $(function () {

    	//touch页面,记录用户进入页面
    	<!--
		$.ajax({
			url : contextPath()+"/mdmis/touch",
			type : "get",
			data : {
				//"traceRandom":trace_random,
    			//"recordID":trace_recordID,
    			"target":location.pathname,
    			"operation":"[进入页面]撸课站-用户状态变更页面"
    		},
			dataType : "json",	// 数据返回类型
            cache : false, 	// 是否缓存
            async : true   	// 默认为true 异步请求
		});
		-->

		//从后台获取到用户状态enum
		$.ajax({
			url : contextPath()+"/airuc/getUserStateEnum",
			type : "get",
			data : {
				//"traceRandom":trace_random,
    			//"recordID":trace_recordID,
    			"target":location.pathname,
    			"operation":"[进入页面]撸课站-用户状态变更页面"
    		},
			dataType : "json",	// 数据返回类型
            cache : false, 	// 是否缓存
            async : true,  	// 默认为true 异步请求
            success: function(res){
                         //UserStateEnum = JSON.parse(res.data); //该语句无法正常执行
                         UserStateEnum = eval('(' + res.data + ')');
                         $('#search_userstatus').combobox({
                         	valueField: 'state',
							textField: 'stateinfo',
							data: UserStateEnum
                         });
                      }
		});

    	$('#datagrid').datagrid({
    		loadMsg:'正在加载数据...',
    	    url:contextPath()+'/airuc/getUserList',
    	    toolbar:'#dgtoolbar',
    	    queryParams: form2Json("searchform"),
    	    pagination: true,
            pageSize:'20',
            pageList:[20,50,100],
            rownumbers: true,
            striped: true,
            fit: true,
            fitColumns: false, //不自动适应列宽
            singleSelect: true, //只能单行选择
            selectOnCheck: true,
            checkOnSelect: true,
			remoteSort: false,
            multiSort: true,
        	sortName : 'create_time',
        	sortOrder : 'asc', //asc正序，desc逆序
    	    columns:[[
    			//{field:'ck',checkbox:true},
    			{field:'username', title:'用户名', halign:'center', aligh:'center', width:100, sortable:true},
    			{field:'name_cn',title:'中文名',halign:'center', width:100},
    			{field:'status',title:'当前状态',halign:'center', width:100,
    			    formatter: function(value,row,index){
    			        if (value) {
							for(i=0; i<UserStateEnum.length; i++) {
	   							if (UserStateEnum[i].state==value) {
	   								return UserStateEnum[i].stateinfo;
	   							}
							}
    			            return "";
    			        } else {
    			            return "";
    			        }
    				}
    			},
    			{field:'create_time',title:'创建时间',halign:'center', sortable:true, width:160},
    			{field:'last_edit_time',title:'最后修改时间',halign:'center', width:160,},
    			{field:'user_id',title:'操作',halign:'left', width:400,
    				formatter: function(value,row,index){
    			        if (value) {
    			        	var str = "";
    			        	for(i=0; i<UserStateEnum.length; i++) {
	   							if (UserStateEnum[i].state == row.status) {
	   								if (UserStateEnum[i].stateinfo == "未注册") {
										str += "<a href='javascript:void(0)' onclick=changeUserStatus('"+index+"','3')>注册</a>";
										str += "&nbsp;|&nbsp;";
	   								} else if (UserStateEnum[i].stateinfo == "未激活") {
										str += "<a href='javascript:void(0)' onclick=changeUserStatus('"+index+"','3')>激活</a>";
										str += "&nbsp;|&nbsp;";
									} else if (UserStateEnum[i].stateinfo == "正常用户") {
										str += "<a href='javascript:void(0)' onclick=changeUserStatus('"+index+"','4')>禁用</a>";
										str += "&nbsp;|&nbsp;";
	   								} else if (UserStateEnum[i].stateinfo == "禁用") {
										str += "<a href='javascript:void(0)' onclick=changeUserStatus('"+index+"','3')>解禁</a>";
										str += "&nbsp;|&nbsp;";
	   								}
	   								break;
	   							}
							}
    			        	str += "<a href='javascript:void(0)' onclick=changeUsername('"+index+"')>修改用户名</a>";
    			        	return str;
    			        } else {
    			            return "";
    			        }
    				}
    			}
    	    ]]
    	});



		//点击搜索
		$("#submit_search").linkbutton({ iconCls: 'icon-search', plain: true }).click(function () {
            $('#datagrid').datagrid({ queryParams: form2Json("searchform") });
        });
		//点击重置
		$("#reset_search").linkbutton({ iconCls: 'icon-reload', plain: true }).click(function () {
            $('#search_username').textbox('setValue',''); //将用户名的输入框清空
            $('#search_name_cn').textbox('setValue',''); //将中文名的输入框清空
            $('#search_userstatus').combobox('clear'); //将用户状态选择框清空
            //$('#datagrid').datagrid('reload');
            $('#datagrid').datagrid({ queryParams: form2Json("searchform") });
        });
    })

    //变更用户状态
    function changeUserStatus(index, status){
    	var rows = $("#datagrid").datagrid('getRows');//获得所有行
		var row = rows[index];
		if (row){
			var status_info = "";
			for(i=0; i<UserStateEnum.length; i++) {
				if (UserStateEnum[i].state == status) {
					status_info = UserStateEnum[i].stateinfo ;
					break;
				}
			}
			$.messager.confirm('Confirm',"确定要将用户【"+row.name_cn+"】状态变更为【"+status_info+"】?",function(r){
				if (r){
					$.post(contextPath()+'/airuc/changeUserStatus',{user_id:row.user_id,status:status},function(result){
						if (result.success){
							$('#datagrid').datagrid('reload');	// reload data
							$.messager.show({
								title: 'Success',
								msg: '操作完成！'
							});
						} else {
							$.messager.show({	// show error message
								title: 'Error',
								msg: result.errMsg
							});
						}
					},'json');
				}
			});
		}
    }

    //修改用户名
    function changeUsername(index, status){
    	var rows = $("#datagrid").datagrid('getRows');//获得所有行
		var row = rows[index];
		if (row){
			$.messager.prompt('Prompt',"将【"+row.name_cn+"】的用户名<br>【"+row.username+"】修改为：",function(r){
				if (r){
					$.post(contextPath()+'/airuc/changeUsername',{user_id:row.user_id,username:r},function(result){
						if (result.success){
							$('#datagrid').datagrid('reload');	// reload data
							$.messager.show({
								title: 'Success',
								msg: '操作完成！'
							});
						} else {
							$.messager.show({	// show error message
								title: 'Error',
								msg: result.errMsg
							});
						}
					},'json');
				}
			});
		}
    }
    
    //将表单数据转为json
    function form2Json(id) {
        var arr = $("#" + id).serializeArray();
        var jsonStr = "";
        jsonStr += '{';
        for (var i = 0; i < arr.length; i++) {
            jsonStr += '"' + arr[i].name + '":"' + arr[i].value + '",'
        }
        jsonStr = jsonStr.substring(0, (jsonStr.length - 1));
        jsonStr += '}';
        var json = JSON.parse(jsonStr);
        return json;
    }

	//将表单数据转为json格式的字符串，当然也可以JSON.stringify(data)
	function form2JsonStr(id) {
		var arr = $("#" + id).serializeArray();
		var jsonStr = "";
		jsonStr += '{';
		for (var i = 0; i < arr.length; i++) {
			jsonStr += '"' + arr[i].name + '":"' + arr[i].value + '",'
		}
		jsonStr = jsonStr.substring(0, (jsonStr.length - 1));
		jsonStr += '}';
		return jsonStr;
	}
    
	</script>
</html>